package com.find.answer.interceptor;

import com.alibaba.fastjson.JSON;
import com.find.answer.domain.http.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author Seon
 * @date 2022/10/16 20:56
 */
@Slf4j
public class LoginCheckInterceptor implements HandlerInterceptor {

    private static final String EMPLOYEE = "employee";

    private static final String NOT_LOGIN = "NOT_LOGIN";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("进入过滤器...");
        HttpSession session = request.getSession();
        Long employeeId = (Long) session.getAttribute(EMPLOYEE);
        log.info("{}", employeeId);
        if (employeeId == null) {
            /*
            如果未登录的话就给前端返回一个json数据，里面是未登录的错误信息。
             */
            response.getWriter().print(JSON.toJSONString(Result.error(NOT_LOGIN)));
//            ServletOutputStream outputStream = response.getOutputStream();
//            String error = JSON.toJSONString(Result.error(NOT_LOGIN));
//            outputStream.write(error.getBytes());

            return false;
        }

        return true;
    }
}
